<?php

namespace common\domain\components\filters;

use common\domain\components\filters\sign\IllegalSignException;
use common\domain\components\filters\sign\SignArgumentException;
use common\domain\helper\Request;
use yii\base\Action;
use yii\base\ActionFilter;

/**
 * Class SignFilter.
 */
class SignFilter extends ActionFilter
{
    /**
     * @param Action $action
     *
     * @return bool
     * @throws SignArgumentException
     * @throws IllegalSignException
     */
    public function beforeAction($action): bool
    {
        $data = Request::getRequest();
        if (!isset($data['sign']) || !$data['sign']) {
            throw new SignArgumentException('Unauthorized', 9001);
        }
        if (!isset($data['timestamp']) || !$data['timestamp']) {
            throw new SignArgumentException('Unauthorized', 9002);
        }
        if (time() - $data['timestamp'] > 600) {
            throw new SignArgumentException('Unauthorized', 9003);
        }

        $sign = $data['sign'];
        unset($data['sign']);
        ksort($data, SORT_NATURAL | SORT_FLAG_CASE);
        $params = http_build_query($data);

        $sign_verify = md5(sha1($params) . AUTH_KEY);

        if ($sign !== $sign_verify) {
            throw new IllegalSignException('Unauthorized', 9000);
        }

        return parent::beforeAction($action);
    }
}
